package service

import (
	"context"

	"gitee.com/WisdomClassroom/ClassStruct/glb"
	"gitee.com/WisdomClassroom/core"
	"gitee.com/WisdomClassroom/core/models"
	"gitee.com/WisdomClassroom/core/protobufs/v1/pb"
	"google.golang.org/grpc/metadata"
	"gorm.io/gorm"
)

func (s *Service) ListClasses(ctx context.Context, request *pb.Empty) (*pb.ListClassesResponse, error) {
	md, ok := metadata.FromIncomingContext(ctx)
	if !ok {
		glb.Logger.Error("no metadata")
	}
	token, err := core.UnpackTokenFromMetadata(md)
	if err != nil {
		return &pb.ListClassesResponse{Status: &pb.ResponseStatus{
			Code: core.ResponseStatusCodeNotAuth, Message: err.Error(),
		}}, nil
	}

	if token.Type != core.UserTypeStudent {
		return &pb.ListClassesResponse{Status: &pb.ResponseStatus{
			Code:    core.ResponseStatusCodeNotAuth,
			Message: "仅学生可调用此接口",
		}}, nil
	}

	student := &models.User{AccountID: token.AccountID}
	err = glb.DB.Preload("Classes").Take(student).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return &pb.ListClassesResponse{Status: &pb.ResponseStatus{
				Code:    core.ResponseStatusCodeOtherError,
				Message: "学生不存在",
			}}, nil
		}
		glb.Logger.Error(err.Error())
		return listClassesRespSvrErr, nil
	}

	classesResp := make([]*pb.ClassBasicInfo, 0, len(student.Classes))
	for _, class := range student.Classes {
		classesResp = append(classesResp, &pb.ClassBasicInfo{
			UUID:        class.UUID,
			Name:        class.Name.String,
			Description: class.Description.String,
			CourseUUID:  class.CourseUUID.String,
		})
	}

	return &pb.ListClassesResponse{
		Status:  &pb.ResponseStatus{Code: core.ResponseStatusCodeSuccess},
		Classes: classesResp,
	}, nil
}
